package iosr11.ui.data;

import iosr11.Service.ServiceLocatorImpl;
import iosr11.Service.EventService;
import iosr11.data.Event;
import iosr11.data.EventSeries;

import java.util.Map;
import java.util.logging.Logger;

import javax.faces.context.FacesContext;

public class EventBean {
	private EventService service;
	private Logger logger = Logger.getLogger("iosr.ui.data");
	private Event event;
	private String eventID;
	
	public EventBean(){
		this.service = (EventService)ServiceLocatorImpl.getInstance().getService(Event.class);
		if(this.service == null){
			logger.severe("Could not obtain reference to EventService");
			return;
		}
		
		Map sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
		if(sessionMap.containsKey(SessionMapKeys.SelectedEventID.name())){ // editing mode
			this.eventID = (String)sessionMap.get(SessionMapKeys.SelectedEventID.name());			
			this.event = service.getEvent(this.eventID);
			
			if(this.event==null){
				logger.severe("Could not obtain student from EventService");
			}
		}else{	// adding new event mode
			this.event = new Event();
			//this.event.setUser(new User());
		}
	}
	
	public boolean getEditMode(){
		return (this.event.getId()!=null);
	}
	
	public String updateEvent(){
		if(this.service.updateEvent(this.event)){
			return "success";
		}else{
			return "failure";
		}
	}
	
	public String addEvent(){
		if(this.service.createEvent(this.event.getStartDate(), this.event.getEndDate(), this.event.getPlace(), (EventSeries)null, this.event.isDeadline(), this.event.getDescription())){
			return "success";
		}else{
			return "failure";
		}
	}
	
	public String delete(){
		if(this.event!=null && this.service.deleteEvent(this.event)){
			return "success";
		}else{
			return "failure";
		}
	}
	
	public Event getEvent(){
		return this.event;
	}
}
